using UnityEngine;

public class Object_ItemPuckup : MonoBehaviour
{
    [SerializeField] private Vector2 dropFroce = new(4, 6);

    [Space]
    [SerializeField] private ItemDataSO itemData;

    private Collider2D col;
    private Rigidbody2D rb;
    private SpriteRenderer spriteRenderer;
    private Inventory_Base inventory;
    private Inventory_Item itemToAdd;


    private void Awake()
    {
        col = GetComponent<Collider2D>();
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }
    
    public void SetupItem(ItemDataSO itemData)
    {
        this.itemData = itemData;

        itemToAdd = new(this.itemData);

        UpdateVisual();

        col.isTrigger = false;
        gameObject.layer = LayerMask.NameToLayer("NoColliderForPlayer");
        //设置x方向随机的掉落力
        float xDropForce = Random.Range(-dropFroce.x, dropFroce.x);
        rb.velocity = new Vector2(xDropForce, dropFroce.y);
    }

    private void UpdateVisual()
    {
        spriteRenderer.sprite = itemData.itemIcon;
        gameObject.name = "Object_ItemPickup - " + itemData.itemName;
    }

    //触发器是Collider2D，碰撞器是Collision2D
    private void OnCollisionEnter2D(Collision2D collsion)
    {
        //当物品掉落到地上之后才能拾取
        if (collsion.gameObject.layer == LayerMask.NameToLayer("Ground") && col.isTrigger == false)
        {
            col.isTrigger = true;
            gameObject.layer = LayerMask.NameToLayer("PlayerInteractable");
            rb.constraints = RigidbodyConstraints2D.FreezeAll;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        inventory = collision.GetComponent<Inventory_Base>();

        if (inventory == null)
            return;

        if (itemData.itemType == ItemType.Material)
        {
            bool isAdd = inventory.storage.TryAddItemToMaterialStorage(itemToAdd);
            if (isAdd == false)
                return;
            gameObject.SetActive(false);
            return;
        }

        if (inventory.CanAddItem(itemToAdd))
        {
            inventory.AddItem(itemToAdd);
            gameObject.SetActive(false);
        }
    }
}
